package plugins.order;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.ClickEvent;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.form.event.ClickEventArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

/**
 * 单据界面插件
 */
public class toCard extends AbstractBillPlugIn implements Plugin {
    private static final String BTN_TOCARD = "dcb4_tocard";
    private static final String FIELD_USER = "dcb4_user";
    private static final String SCHOOLCARD_FORMID = "dcb4_schoolcard"; // 目标表单标识


    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);

        if (BTN_TOCARD.equals(evt.getItemKey())) {
            IDataModel model = this.getModel();
            // 1. 获取当前单据的dcb4_user字段值
            DynamicObject userObj = (DynamicObject) model.getValue(FIELD_USER);
            if (userObj == null) {
                this.getView().showTipNotification("请先选择用户");
                return;
            }
            Object userId = userObj.getPkValue();

            // 2. 构建查询条件：dcb4_schoolcard中dcb4_user=当前用户ID
            QFilter filter = new QFilter("dcb4_user", QFilter.equals, userId);

            // 3. 查询dcb4_schoolcard记录
            DynamicObject[] schoolCards = BusinessDataServiceHelper.load(
                    SCHOOLCARD_FORMID,
                    "id",
                    new QFilter[]{filter}
            );

            if (schoolCards == null || schoolCards.length == 0) {
                this.getView().showTipNotification("未找到关联的校园卡记录");
                return;
            }

            // 4. 获取第一条记录ID（根据需求唯一）
            Object schoolCardId = schoolCards[0].getPkValue();

            // 5. 打开校园卡表单 - 使用BillShowParameter
            BillShowParameter showParam = new BillShowParameter();
            showParam.setFormId(SCHOOLCARD_FORMID);
            showParam.setPkId(schoolCardId); // 正确的方法
            showParam.getOpenStyle().setShowType(ShowType.Modal);
            this.getView().showForm(showParam);
        }
    }
}